package acs.http;

import java.util.HashMap;
import java.util.Map;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.controller.MessageObserver;
import acs.offer.util.CollectionUtil;
import acs.offer.util.ServerCache;
/**
 * 控制到了请求类型层
 * @author Administrator
 *
 */
public class DmsService {
	
	private MessageObserver observer;// 状态
	
	private Map<String,DmsTask> taskMap=new HashMap<>();
	private volatile boolean isRemoveTask=false;

	/**
	 * 得到前面生成的task
	 * @param param
	 * @return
	 */
	private DmsTask getPreTask(Params param) {
		String requestUri=param.get(Constant.REQUEST_URI);
		DmsTask task=taskMap.get(requestUri);
		return task;
	}
	/**
	 * 获取或创建一个新的task
	 * @param param
	 * @return
	 */
	private DmsTask getOrgeneratorTask(Params param) {
		while(isRemoveTask){};
		String requestUri=param.get(Constant.REQUEST_URI);
		DmsTask task=taskMap.get(requestUri);
		if(task == null) {
			task=new DmsTask();
			taskMap.put(requestUri,task);
			DMSSoftTimer.getInstance().startTimer(Constant.MAX_WAIT_TASK_TIME, EventType.REMOVE_TASK,param);//到期删除对应的task
		}
		return task;
	}
	

	/**
	 * 移除task
	 * @param params
	 */
	public void removeTask(Params params) {
		this.isRemoveTask=true;
		try {
			String requestUri=params.get(Constant.REQUEST_URI);
			DmsTask dmsTask = taskMap.get(requestUri);
			if(dmsTask == null) {
				return ;
			}
			if(CollectionUtil.isEmpty(dmsTask.getParamsList())) {//没有待处理的请求
				taskMap.remove(requestUri);
			}else {//有待处理的请求
				if((System.currentTimeMillis() - dmsTask.getRequestTime()) < Constant.MAX_WAIT_DATA_TIME) {
					DMSSoftTimer.getInstance().startTimer(Constant.MAX_WAIT_TASK_TIME, EventType.REMOVE_TASK,params);//开始清除缓存倒计时
				}else {//请求超时了，直接remove
					taskMap.remove(requestUri);
				}
			}
		}finally {
			this.isRemoveTask=false;
		}
	}
	 /**
     * 移除缓存
     * @param param
     */
	public void clearCache(Params param) {
        ServerCache serverCache = ServerCache.getInstance();
        String cacheKey = serverCache.getCacheKey(param);
        serverCache.remove(cacheKey);//清除缓存
        //将dmsServer 的状态变为初始状态
    }
	/**
	 * 给客户端响应数据
	 * @param param
	 */
	public void sendResponse(Params param) {
		HttpServerHandler.sendMessage(param);
	}
	/**
	 * 处理请求
	 * @param param
	 */
	public void handleRequest(Params param) {
		DmsTask task = this.getOrgeneratorTask(param);
		task.loadData(param);
	}
	/**
	 * 服务端获取数据超时了，不给客户端响应数据了
	 * @param param
	 */
	public void doNotResponseDataToClient(Params param) {
		//移除客户端channel，防止内存泄漏
		System.out.println("请求数据超时，移除channel ");
		HttpServerHandler.removeChannel(param);
	}

	
	
	public DmsService(MessageObserver observer) {
		super();
		this.observer = observer;
	}
    
}
